<?php


namespace app\back\model;


use \Exception;
use think\facade\Db;
use think\response\Json;

class OrgModel
{
    private static $_table = 'organization'; // 机构表
    private static $_adminTable = 'admin'; // 管理员表
    private static $_driverTable = 'driver'; // 司机表
    private static $_driverRouteTable = 'driver_route'; // 司机路线表

    /**获取机构列表
     * @param $input
     * @param $info
     * @return Json
     */
    public static function getOrgList($input, $info)
    {
        try {
            $map = [
                ['o.admin_id', '=', $info['id']]
            ];
            if ($input['type'] !== '') {
                $map[] = ['o.type', '=', $input['type']];
            }
            if ($input['status'] !== '') {
                $map[] = ['o.status', '=', $input['status']];
            } else {
                $map[] = ['o.status', 'in', [1,2]];
            }
            if ($input['name'] !== '') $map[] = ['o.name', 'like', "%{$input['name']}%"];
            $field = 'o.id,o.name,o.status,o.create_time,a.name as bind_name,o.type,o.longitude,o.latitude,o.province,o.city,o.area,o.address,o.detail,d.name as driver_name';
            $table = Db::table(self::$_table)->alias('o')
                ->join([self::$_adminTable => 'a'] , 'a.id = o.bind_id')
                ->leftJoin([self::$_driverTable => 'd'] , 'd.id = o.driver_id')
                ->where($map)->field($field);
            $count = $table->count();
            if ($count == 0) return jsonSuccess('暂无数据', ['count' => 0,'list' => []]);
            $list = $table->page($input['page'], $input['limit'])->order('create_time', 'desc')->select()->toArray();
            return jsonSuccess('获取成功', ['count' => $count, 'list' => $list]);
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**添加机构
     * @param $input
     * @param $info
     * @return Json
     */
    public static function addOrg($input,$info)
    {
        $flag = false;
        try {
            $input['admin_id'] = $info['id'];
            $input['create_time'] = time();
            $input['driver_id'] = $input['type'] == 2 ? 0 : $input['driver_id'] ;
            Db::startTrans();
            $flag = true;
            $moveId = Db::table(self::$_table)->insertGetId($input);
            if ($moveId < 1) {
                Db::rollback();
                return jsonFail('添加失败');
            }
            // 添加司机路线
            if (in_array($input['type'], [1,3])) {
                // 社区 合作社绑定司机
                $data = [
                  'move_id' => $moveId,
                  'driver_id' => $input['driver_id'],
                  'type' => $input['type']
                ];
                $rtn = Db::table(self::$_driverRouteTable)->insert($data);
                if ($rtn != 1) {
                    Db::rollback();
                    return jsonFail('添加失败');
                }
            } else {
                // 分拣中心绑定司机
                $map = [
                    ['admin_id', '=', $info['id']],
                    ['status', 'in', [1,2]]
                ];
                $driverInfos = Db::table(self::$_driverTable)->field('id as driver_id')->where($map)->select()->toArray();
                if ($driverInfos) {
                    foreach ($driverInfos as &$driverInfo) {
                        $driverInfo['move_id'] = $moveId;
                        $driverInfo['type'] = 2;
                    }
                    $rtn = Db::table(self::$_driverRouteTable)->insertAll($driverInfos);
                    if ($rtn != count($driverInfos)) {
                        Db::rollback();
                        return jsonFail('添加失败');
                    }
                }
            }
            Db::commit();
            return jsonSuccess('添加成功');
        } catch (Exception $e) {
            if ($flag == true) Db::rollback();
            var_dump($e->getMessage());
            return jsonFail('服务内部错误~');
        }
    }

    /**修改机构状态
     * @param $input
     * @param $info
     * @return Json
     */
    public static function changeOrgStatus($input,$info)
    {
        $flag = false;
        try {
            // 获取当前信息
            $orgInfo = Db::table(self::$_table)->field('admin_id,status')->where('id', $input['id'])->find();
            if (!$orgInfo) return jsonFail('未找到机构信息');
            if ($orgInfo['admin_id'] != $info['id']) return jsonFail('该机构非您直接管理，您没有权限操作');
            if ($orgInfo['status'] == 3) return jsonFail('该机构已删除无法继续操作');
            // 根据不同status执行不同操作
            Db::startTrans();
            $flag = true;
            $update = [
                'status' => $input['status']
            ];
            $map = [
                ['id', '=', $input['id']],
                ['admin_id', '=', $info['id']],
                ['status','=', $input['status'] == 1? 2:1]
            ];
            $rtn = Db::table(self::$_table)->where($map)->update($update);
            if (!$rtn) {
                Db::rollback();
                return  jsonFail('操作失败,请点击刷新按钮重新查看');
            }
            // 修改路线状态
            $map = [
                ['move_id', '=', $input['id']],
                ['status', '=', $input['status'] == 1 ? 2 : 1]
            ];
            $count = Db::table(self::$_driverRouteTable)->where($map)->count();
            $rtn = Db::table(self::$_driverRouteTable)->where($map)->update(['status' => $input['status']]);
            if ($rtn != $count) {
                Db::rollback();
                return  jsonFail('操作失败,请点击刷新按钮重新查看');
            }
            Db::commit();
            return jsonSuccess('修改成功');
        } catch (Exception $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**删除机构（软删除）
     * @param $input
     * @param $info
     * @return Json
     */
    public static function delOrg($input,$info)
    {
        $flag = false;
        try {
            // 获取当前信息
            $orgInfo = Db::table(self::$_table)->field('admin_id,status')->where('id', $input['id'])->find();
            if (!$orgInfo) return jsonFail('未找到机构信息');
            if ($orgInfo['admin_id'] != $info['id']) return jsonFail('该机构非您直接管理，您没有权限操作');
            if ($orgInfo['status'] == 3) return jsonFail('该机构已删除无法继续操作');
            // 根据不同status执行不同操作
            Db::startTrans();
            $flag = true;
            $map = [
                ['id', '=', $input['id']],
                ['admin_id', '=', $info['id']],
                ['status','in', [1,2]]
            ];
            $rtn = Db::table(self::$_table)->where($map)->update(['status' => 3]);
            if (!$rtn) {
                Db::rollback();
                return  jsonFail('操作失败,请点击刷新按钮重新查看');
            }
            // 修改路线状态
            $map = [
                ['move_id', '=', $input['id']],
                ['status', '<>', 3]
            ];
            $count = Db::table(self::$_driverRouteTable)->where($map)->count();
            $rtn = Db::table(self::$_driverRouteTable)->where($map)->update(['status' => 3]);
            if ($rtn != $count) {
                Db::rollback();
                return  jsonFail('操作失败,请点击刷新按钮重新查看');
            }
            Db::commit();
            return jsonSuccess('删除成功');
        } catch (Exception $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**获取单个机构信息
     * @param $input
     * @param $info
     * @return Json
     */
    public static function getOrgOnly($input,$info)
    {
        try {
            // 获取当前信息
            $orgInfo = Db::table(self::$_table)->field('id,admin_id,bind_id,name,type,longitude,latitude,province,city,area,address,detail,status')->where('id', $input['id'])->find();
            if (!$orgInfo) return jsonFail('未找到机构信息');
            if ($orgInfo['admin_id'] != $info['id']) return jsonFail('该机构非您直接管理，您没有权限操作');
            if ($orgInfo['status'] == 3) return jsonFail('该机构已删除无法继续操作');
            $adminList = AdminModel::getAdminSimpleStatic($info);
            if (!is_array($adminList)) return $adminList;
            unset($orgInfo['admin_id']);
            unset($orgInfo['status']);
            return jsonSuccess('获取成功', ['info' => $orgInfo, 'adminList' => $adminList]);
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**编辑机构
     * @param $input
     * @param $info
     * @return Json
     */
    public static function editOrg($input,$info)
    {
        try {
            // 获取当前信息
            $orgInfo = Db::table(self::$_table)->field('admin_id,status')->where('id', $input['id'])->find();
            if (!$orgInfo) return jsonFail('未找到机构信息');
            if ($orgInfo['admin_id'] != $info['id']) return jsonFail('该机构非您直接管理，您没有权限操作');
            if ($orgInfo['status'] == 3) return jsonFail('该机构已删除无法继续操作');

            $rtn = Db::table(self::$_table)->update($input);
            if ($rtn) return jsonSuccess('操作成功');
            return jsonFail('操作失败,请点击刷新按钮重新查看');
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**获取相关附属信息(内部调用)
     * @param $info
     * @return Json|array
     */
    public static function getOtherStatic($info)
    {
        try {
            // 获取管理员
            $map = [
                ['pid', '=', $info['id']],
                ['status', '=', 1]
            ];
            $adminInfo = Db::table(self::$_adminTable)->field('id,name')->where($map)->select()->toArray();
            if (!$adminInfo) return jsonFail('未找到可用的管理员,请先添加管理员');
            // 获取司机信息
            $map = [
                ['admin_id', '=', $info['id']],
                ['status', '=', 1]
            ];
            $driverInfo = Db::table(self::$_driverTable)->field('id,name')->where($map)->select()->toArray();
            if (!$driverInfo) return jsonFail('未找到可用的司机,请先添加司机');
            return ['adminInfo' => $adminInfo, 'driverInfo' => $driverInfo];
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**获取相关附属信息
     * @param $info
     * @return Json
     */
    public static function getOther($info)
    {
        $rtn = self::getOtherStatic($info);
        if (is_array($rtn)) return jsonSuccess('获取成功',$rtn);
        return $rtn;
    }
}